package com.suxin.socket.yinfei.session;

import lombok.Getter;
import org.apache.kafka.common.utils.CopyOnWriteMap;

import javax.websocket.Session;
import java.util.Arrays;
import java.util.Collection;
import java.util.concurrent.CopyOnWriteArraySet;
import java.util.stream.Collectors;

/**
 * @author Tang
 * @classname ParameterSessionConnectionHolder
 * @description [ 有参 ]
 * @date 2021/8/17 22:34
 */
public class ParameterSessionConnectionHolder extends AbstractSessionConnectionHolder {

    @Getter
    private static CopyOnWriteMap<String, CopyOnWriteArraySet<Session>> sessions = new CopyOnWriteMap<>();

    /**
     * 分隔符
     */
    private String delimiter;

    /**
     * 参数标识符
     */
    private String[] identifier;


    public ParameterSessionConnectionHolder(String... identifier) {
        this("", identifier);
    }

    public ParameterSessionConnectionHolder(String delimiter, String... identifier) {
        this.delimiter = delimiter;
        this.identifier = identifier;
    }

    @Override
    public void onOpen(Session session) {
        super.onOpen(session);
        String keyStr = Arrays.stream(identifier).map(item -> session.getPathParameters().get(item))
                .collect(Collectors.joining(this.delimiter));
        sessions.compute(keyStr, (key, value) -> sessions.getOrDefault(key,new CopyOnWriteArraySet<Session>()));
    }

    @Override
    public void onClose(Session session) {
        super.onClose(session);
    }

    @Override
    public Collection<Session> getSession(String identify) {
        return sessions.get(identify);
    }
}